<?php

/*
 * This file is part of ibrand/EC-Open-Server.
 *
 * (c) iBrand <https://www.ibrand.cc>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace iBrand\EC\Open\Server\Http\Controllers;

use DB;
use EasyWeChat;
use iBrand\Component\Category\RepositoryContract as CategoryRepository;
use iBrand\Component\Discount\Repositories\CouponRepository;
use iBrand\Component\Product\AttributeRelation;
use iBrand\Component\Product\Models\Attribute;
use iBrand\Component\Product\Models\Specification;
use iBrand\Component\Product\Models\SpecificationRelation;
use iBrand\Component\Product\Models\SpecificationValue;
use iBrand\Component\Product\Repositories\GoodsRepository;
use iBrand\EC\Open\Backend\Store\Repositories\CommentsRepository;
use iBrand\EC\Open\Core\Services\DiscountService;
use iBrand\EC\Open\Server\Transformers\GoodsTransformer;
use iBrand\Miniprogram\Poster\MiniProgramShareImg;
use Storage;

class GoodsController extends Controller
{
    protected $goodsRepository;
    protected $couponRepository;
    protected $categoryRepository;
    protected $commentsRepository;

    public function __construct(GoodsRepository $goodsRepository,
                                CouponRepository $couponRepository,
                                CategoryRepository $categoryRepository,
                                CommentsRepository $commentsRepository
    )
    {
        $this->goodsRepository = $goodsRepository;
        $this->couponRepository = $couponRepository;
        $this->categoryRepository = $categoryRepository;
        $this->commentsRepository = $commentsRepository;
    }

    /**
     * @return \Dingo\Api\Http\Response|mixedc
     * 查询商品评论
     */
    public function getComments(){
        $goods_id = request('goods_id',0);
        if(!$goods_id){
            return $this->failed('缺少信息！');
        }
        $res = DB::table('ibrand_order_comment')->where(['item_id'=>$goods_id,'status'=>'show'])->orderBy('recommend',"DESC")->get(['user_id','contents','pic_list']);
        if(!$res){
            return $this->success([]);
        }
        foreach ($res as &$v){
            $v->image = unserialize($v->pic_list);
            unset($v->pic_list);
            $user_info = DB::table('ibrand_user')->where(['id'=>$v->user_id])->first(['id','name','avatar']);
            $v->user_info = $user_info;
        }
        return $this->success($res);
    }


    /**
     * @return \Dingo\Api\Http\Response
     * 商品列表
     */
    public function indexs(){
        $goodsCategoryTable = config('ibrand.app.database.prefix', 'ibrand_') . 'goods_category';
        $categoryId = request('c_id',0);
        $orderBy = request('orderBy') ? request('orderBy') : 'sort';
        $sort = request('sort') ? request('sort') : 'asc';

        //查出所有的分类
        $where =[];
        if($categoryId && $categoryId != 1){
            $where = ['category_id'=>$categoryId];
        }
        //查询分类
        $category = DB::table('ibrand_category')->leftjoin($goodsCategoryTable,'ibrand_category.id','=',"$goodsCategoryTable.category_id")->where($where)->where('sort','!=',0)->orderBy('sort','asc')->get()->toArray();
        //查询商品信息
        $categoryIds = array_column($category,'goods_id');
        if($categoryIds || $categoryId ==1){
            //5. get goods list
            $goodsList = $this->goodsRepository->scopeQuery(function ($query) use ($categoryIds) {
                if (!empty($categoryIds)){
                    $query = $query->whereIn('id', $categoryIds);
                }
                if (!empty(request('price'))) {
                    list($min, $max) = explode('-', request('price'));
                    $query = $query->where('sell_price', '>=', $min);
                    $query = $query->where('sell_price', '<=', $max);
                }

                if (!empty($keyword = request('keyword'))) {
                    $query = $query->where(function ($query) use ($keyword) {
                        $query->where('name', 'like', '%' . $keyword . '%')->orWhere('tags', 'like', '%' . $keyword . '%');
                    });
                }
                $query->where('newcomer_price','=',NULL);
                return $query->where(['is_del' => 0, 'is_largess' => request('is_largess') ? request('is_largess') : 0]);
            })->orderBy($orderBy, $sort)->all();

            $goods_trans = new GoodsTransformer();
            foreach ($goodsList as &$v){
                $v['product'] = $goods_trans->includeProducts($v);
                foreach ($v['products'] as &$item){
                    //$spec_ids = $item['spec_ids'][0];
                    $spec_info = DB::table('ibrand_goods_spec_value')->whereIn('id',$item['spec_ids'])->get(['name'])->toArray();
                    if($spec_info){
                        $spec_name_arr = array_column($spec_info,'name');
                        $spec_name = implode(' ',$spec_name_arr);
                        $item['spec_name'] = $spec_name;
                    }

                }
                unset($v['product']);
            }
            return $this->success($goodsList);
        }else{
            return $this->success([]);
        }


    }



    public function newComerGoodsLists(){
        $user = request()->user();
        $categoryIds = [10,11];
        $goodsList = $this->goodsRepository->scopeQuery(function ($query) use ($categoryIds) {
            if (!empty($categoryIds)){
                $query = $query->where('newcomer_price', '!=',NULL);
            }
            return $query->where(['is_del' => 0, 'is_largess' => request('is_largess') ? request('is_largess') : 0]);
        })->all(['id','name','sell_price','newcomer_price','market_price','img','sub_name']);
        $goods_trans = new GoodsTransformer();
        foreach ($goodsList as &$v){
            $v['product'] = $goods_trans->includeProducts($v);
            foreach ($v['products'] as &$item){
                $spec_info = DB::table('ibrand_goods_spec_value')->whereIn('id',$item['spec_ids'])->get(['name'])->toArray();
                if($spec_info){
                    $spec_name_arr = array_column($spec_info,'name');
                    $spec_name = implode(' ',$spec_name_arr);
                    $item['spec_name'] = $spec_name;
                }

            }
            unset($v['product']);
        }
        //查询是否是新人
        $res = DB::table('ibrand_order')->where(['type'=>2,'user_id'=>$user->id])->where('status','!=',1)->first();
        $data['is_new'] = $res?0:1;
        $data['title'] = '新人专区商品';
        $data['sub_title'] = '';
        $data['goods_list'] = $goodsList;
        return $this->success($data);
    }

    public function goodsDetail()
    {
        $id = request('goods_id');
        if(!$id){
            return $this->failed('缺少参数');
        }
        $goods = $this->goodsRepository->find($id);

        $goods_trans = new GoodsTransformer();
        $goods['product'] = $goods_trans->includeProducts($goods);
        foreach ($goods['products'] as &$item){
            //$spec_ids = $item['spec_ids'][0];
            $spec_info = DB::table('ibrand_goods_spec_value')->whereIn('id',$item['spec_ids'])->get(['name'])->toArray();
            if($spec_info){
                $spec_name_arr = array_column($spec_info,'name');
                $spec_name = implode(' ',$spec_name_arr);
                $item['spec_name'] = $spec_name;
            }

        }
        $goods['photo'] = $goods_trans->includePhotos($goods);
        foreach ($goods['photos'] as &$items){
            unset($items['deleted_at']);
        }
        unset($goods['product']);
        unset($goods['photo']);
        preg_match_all("/[a-z]+:\/\/[a-z0-9_\-\/.%]+/i",$goods['contentpc'],$array2);
        $goods['contentpc'] = isset($array2[0][0])?$array2[0][0]:'';
        return $this->success($goods);
    }

    public function show($id)
    {

        $goods = $this->goodsRepository->find($id);
        //获取优惠折扣
        $discounts = app(DiscountService::class)->getDiscountsByGoods($goods);
        if (!$discounts || count($discounts) == 0) {
            $result = null;
        } else {
            $result['discounts'] = collect_to_array($discounts->where('coupon_based', 0));
            $result['coupons'] = collect_to_array($discounts->where('coupon_based', 1));
        }

        return $this->response()->item($goods, new GoodsTransformer())
            ->setMeta(['attributes' => $goods->attr, 'discounts' => $result]);
    }
}
